package pack1;

import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.swim.entity.RegisteredUser;
import com.swim.session.RegisteredUserRemote;

/**
 * Gestisce il login degli utenti
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
    
    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "/WEB-INF/noauth/login.jsp";
		Object auth = request.getSession().getAttribute("authenticated");
		

		if(auth != null && (boolean)auth) {
			url ="index.jsp";
		}
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
				
			String email = request.getParameter("email");
			String password = request.getParameter("password");
			String url = "/WEB-INF/noauth/login.jsp";

			if(email == null || password == null) {
				Object auth = request.getSession().getAttribute("authenticated");
				if(auth != null && (boolean)auth) {
					url ="index.jsp";
				}
				RequestDispatcher dispatcher = request.getRequestDispatcher(url);
				dispatcher.forward(request, response); 
			} else {
				//add user to DB
				response.setContentType("text/html");
				if(email == null || email.length() <= 0) {
					request.setAttribute("title","Login Error");
					request.setAttribute("message","There was an error during the login. Go <a href=\"login.jsp\">back</a> to the login page or <a href=\"index.jsp\">home</a>.");
					RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/target.jsp");
					dispatcher.forward(request, response); 
					return;
				}
				try {
					InitialContext jndiContext = (InitialContext) Util.getInitialContext();
					Object ref = jndiContext.lookup("RegisteredUserBeanJNDI");
					RegisteredUserRemote r = (RegisteredUserRemote) ref;

					//r.initDb();
					RegisteredUser user = r.getUserWithEmail(email);
					HttpSession session = request.getSession();
					if(user == null) {
						request.setAttribute("title","Login Error");
						request.setAttribute("message","There was an error during the login. Go <a href=\"login.jsp\">back</a> to the login page or <a href=\"index.jsp\">home</a>.");
						RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/target.jsp");
						dispatcher.forward(request, response); 
						return;
					}
					if(user != null && !user.getPassword().equals(password)) {
						//set authentication to true
						int fail = 0;
						
						if(session.getAttribute("failed") != null)
							fail = (int) session.getAttribute("failed");
						fail++;
						session.setAttribute("failed",fail);
						if(fail>=3) {
							request.setAttribute("title","Login Error");
							request.setAttribute("message","<p>Three consecutive failed logins. You deserve this.</p>" +
									"<div><iframe width=\"640\" height=\"480\" src=\"http://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1\" frameborder=\"0\" allowfullscreen></iframe></div>" +
									" <p>Go <a href=\"login.jsp\">back</a> to the login page or <a href=\"index.jsp\">home</a>.</p>");
							RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/target.jsp");
							dispatcher.forward(request, response);
						}else{
							request.setAttribute("title","Login Error");
							request.setAttribute("message","There was an error during the login. Go <a href=\"login.jsp\">back</a> to the login page or <a href=\"index.jsp\">home</a>.");
							RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/target.jsp");
							dispatcher.forward(request, response); 
						}
						return;
					}
					session.setAttribute("failed",0);
					
					//set authentication to true
					session.setAttribute("authenticated", true);
					session.setAttribute("authenticated-email", email);
					session.setAttribute("admin", user.isAdmin());
					
					response.sendRedirect("index.jsp");
					
				} catch (NamingException e) {
					e.printStackTrace();
				}

			}
		} catch (Exception e) {
			request.setAttribute("title","Login error!");
			request.setAttribute("message","<p>There was an error during the login.</p>" +
					"<p>Go back to the <a href=\"login.jsp\">login</a> page to login again or <a href=\"registration.jsp\">register</a> with another email.</p>");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/target.jsp");
			dispatcher.forward(request, response); 
		}
	}
	
}
